package com.modbus;

import com.modbus.entity.ModbusFrame;
import com.modbus.entity.ModbusHeader;
import com.modbus.entity.func.response.ReadCoilsResponse;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.BitSet;

/**
 * @author heyayun
 * @description modbus tcp 工具类
 * @date 2021/3/23 15:31
 */
@Slf4j
@Component
public class ModbusTcpUtil {
    @Autowired
    private ModbusMasterServer modbusMasterServer;
    @Autowired
    private ModbusServer modbusServer;
    /**
     * 读取Coils开关量
     *
     * @param address
     *            寄存器开始地址
     * @param quantity
     *            数量
     * @param unitId
     *            ID
     * @return 读取值
     */
    public Boolean readCoils(int address, int quantity, int unitId){
        Boolean result = null;
        ChannelGroup clientChannels = modbusServer.getClientChannels();
        // 创建响应方式
        BitSet coilStatus = new BitSet(1);
        coilStatus.set(0);
        coilStatus.set(5);
        coilStatus.set(8);
        ReadCoilsResponse response = new ReadCoilsResponse(coilStatus);
        ModbusHeader headers = new ModbusHeader(
                3,
                0,
                response.calculateLength(),
                (short) 2);

        ModbusFrame responseFrame = new ModbusFrame(headers, response);
        clientChannels.writeAndFlush(responseFrame);
        return result;
    }
}
